# -*- coding:utf8 -*-

class Solution(object):
    def threeSumClosest(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        length = len(nums)
        result = nums[0]+ nums[1]+nums[len(nums)-1]
        nums = sorted(nums)
        for i in xrange(0,length-2):
            start = i+1
            end = length-1
            while start< end:
                total = nums[i]+nums[start]+nums[end]
                if (total>target):
                    end-=1
                else:
                    start+=1
                if abs(total-target) < abs(result-target):
                    result=total
        return result

    

if __name__ == "__main__":
    print Solution().threeSumClosest([-1,2,1,-4],1)